package org.vectrics.recruiter.web;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.vectrics.SystemException;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitStart;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.recruiter.web.RecruitWebTestPrepare;
import org.vectrics.struts.HttpRequestConverter;
import org.vectrics.struts.Request;
import org.vectrics.user.Person;
//import org.vectrics.user.UserAuthService;
import org.vectrics.common.http.HttpUtils;
import org.vectrics.hibernate.ThreadProperties;



public class TestPrepServlet extends HttpServlet {

	private static final long serialVersionUID = -7946773224794457198L;
	
	private static final String CONTENT_TYPE = "text/html";
    private transient static Logger log = Logger.getLogger(TestPrepServlet.class);
    private boolean initialized = false;

    
    protected void showSessionInformation(Request request) {
    	if (log.isDebugEnabled())
    		HttpUtils.logRequestInfo(request, log, Level.DEBUG);
    }
    
    /**Initialize global variables*/
    public synchronized void init() throws ServletException {
    	super.init();
    	try {
	    	
	        log.info("TestPrepServlet initializing.");
	        initialized = true;
	        RecruitStart.getInstance().initializeWebApplication(this.getServletContext());
    	} catch (Exception ex) {
    		log.error("Exception initializing servlet", ex);
    		throw new ServletException("Exception initializing servlet", ex);
    	}
    }

	/**Process the HTTP Get request*/
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);        
	}


	/**Process the HTTP Post request*/
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);        
	}
	
	
	public void service(HttpServletRequest httpRequest, HttpServletResponse response) throws ServletException, IOException {
		Request request = HttpRequestConverter.convertRequest(httpRequest);
		try {
			checkForLogin(request);
			Person user = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(ThreadProperties.getDomain(), request);
			String userName = "none";
			if (user != null)	
				userName = user.getUser().getUserName();
			log.info("Request: " + request.getRequestURI() + "  User: " + userName 
			        + "  Remote Address: " + request.getRemoteAddr());
			if (log.isDebugEnabled()) {
				showSessionInformation(request);
			}
			if (request.getRequestURI().indexOf("testinfo.xml") >= 0) {
				RecruitWebTestPrepare prepare = new RecruitWebTestPrepare();
				prepare.handlePrepRequest(request, response);
			} else {
				log.info("Could not handle request");
			}
		}
		catch (Exception ex) {
			log.error("Exception caught by servlet", ex);
			throw new ServletException(ex);
		}        
	}

	private void checkForLogin(Request request) {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		if ((password != null) && (password.trim().length() > 0)) {
			if ((userName != null) && (userName.trim().length() > 0)) {
				log.info("Logging in user");
				Person person = CoreServiceLocator.getPersonService().findPersonWithUserName(ThreadProperties.getDomain(), userName);
				if ((person != null) && (person.getUser() != null) && (password != null)) {
				    boolean validCredentials = false;
				    if ((password != null) && (person.getUser().getPassword().equals(password))) {
				        validCredentials = true;
				    }
				    if (validCredentials) {
						String server = RecruitConfig.getRecruitInstance().getServerIp();
						CoreServiceLocator.getUserAuthService()
							.loginUser(request, server, request.getContextPath(), person);
						log.info("Login Complete!");
				    } else {
				        log.info("Credentials not valid");
				        throw new SystemException("Test user's credentials not valid: " + userName);
				    }
				} else {
				    throw new SystemException("Could not find user: " + userName);
				}
			}
		}
	}

}